package com.littcore.saap.mgr.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.littcore.cache.SimpleCacheManager;
import com.littcore.dao.page.IPageList;
import com.littcore.dao.ql.PageParam;
import com.littcore.exception.NotLoginException;
import com.littcore.module.annotation.Func;
import com.littcore.saap.assistant.webservice.IQuickviewWebService;
import com.littcore.saap.common.vo.LoginUserVo;
import com.littcore.saap.common.vo.TenantUserVo;
import com.littcore.saap.core.common.SaapConstants;
import com.littcore.saap.core.common.SaapConstants.IsolatedMode;
import com.littcore.saap.core.common.SaapConstants.TenantOrderType;
import com.littcore.saap.core.common.SaapConstants.TenantStatus;
import com.littcore.saap.core.module.tenant.config.TenantDefConfig;
import com.littcore.saap.core.module.tenant.config.TenantMetaConfigManager;
import com.littcore.saap.core.module.tenant.config.TenantTypeConfigManager;
import com.littcore.saap.core.module.tenant.config.meta.TenantMetaAttr;
import com.littcore.saap.core.module.tenant.config.meta.TenantMetaAttrGroup;
import com.littcore.saap.core.web.util.LoginUtils;
import com.littcore.saap.mgr.service.ITenantConfigMgrService;
import com.littcore.saap.mgr.service.ITenantMemberMgrService;
import com.littcore.saap.mgr.service.ITenantMgrService;
import com.littcore.saap.mgr.service.ITenantOrderMgrService;
import com.littcore.saap.mgr.service.IUserGroupMgrService;
import com.littcore.saap.mgr.service.IUserInfoMgrService;
import com.littcore.saap.system.biz.ITenantBizService;
import com.littcore.saap.system.biz.IUserBizService;
import com.littcore.saap.system.po.Role;
import com.littcore.saap.system.po.Tenant;
import com.littcore.saap.system.po.TenantMember;
import com.littcore.saap.system.po.TenantOrder;
import com.littcore.saap.system.po.UserGroup;
import com.littcore.saap.system.po.UserInfo;
import com.littcore.saap.system.vo.TenantConfigVo;
import com.littcore.web.mvc.action.BaseController;
import com.littcore.web.util.WebUtils;

/**
 * TenantController.
 * 
 * <pre>
 * <b>描述：</b>
 * 
 * </pre>
 * 
 * <pre>
 * <b>修改记录：</b>
 * 
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">蔡源</a>
 * @since 2014年2月27日
 * @version 1.0
 */
@Controller
@RequestMapping(value = "/tenantMgr")
public class TenantMgrController extends BaseController {

	@Resource
	private ITenantMgrService tenantMgrService;
	@Resource
	private ITenantConfigMgrService tenantConfigMgrService;
	@Resource
	private ITenantMemberMgrService tenantMemberMgrService;
	@Resource
	private IQuickviewWebService quickviewService;
	@Resource
	private IUserInfoMgrService userInfoMgrService;
	@Resource
	private IUserBizService userBizService;
	@Resource
	private IUserGroupMgrService userGroupMgrService;
	@Resource
	private ITenantBizService tenantBizService;
	@Resource
	private ITenantOrderMgrService tenantOrderMgrService;
	

	@Func(funcCode = "query", moduleCode = "mgr.tenant", enableLog = false)
	@RequestMapping
	public ModelAndView index(WebRequest request, ModelMap modelMap) throws NotLoginException
	{	
		LoginUserVo loginUserVo = (LoginUserVo)super.getLoginVo();
		
		//读取快速视图定义		
		Map<String, Object> resultMap = quickviewService.generate("tenantMgr-quickview", loginUserVo, request);    
	    modelMap.addAllAttributes(resultMap);
			
	    return new ModelAndView("/mgr/tenant/index");
	}  
	
	
	/**
	 * 工作空间价格表.
	 *
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@Func(funcCode = "edit", moduleCode = "mgr.tenant", enableLog = false)
	@RequestMapping
	public ModelAndView priceTable() throws Exception{   
		
	    TenantDefConfig[] tenantDefList = TenantTypeConfigManager.getInstance().getConfig().getTenantDefList();    
	    
	    return new ModelAndView("/mgr/tenant/priceTable")
	          .addObject("tenantDefList", tenantDefList);   
	}
	
	
	
	/**
	 * 新租户订单订单
	 * 
	 * @param tenantTypeCode
	 * @return
	 * @throws Exception
	 */
	@Func(funcCode = "add", moduleCode = "mgr.tenant", enableLog = false)
	@RequestMapping
	public ModelAndView order(@RequestParam String tenantTypeCode) throws Exception {
		
	    TenantDefConfig tenantDef = TenantTypeConfigManager.getInstance().getTenantDefConfig(tenantTypeCode);
	    List<UserInfo> userInfoList = userInfoMgrService.listAll();
	    
	    return new ModelAndView("/mgr/tenant/order")
	    		.addObject("tenantDef", tenantDef)
	    		.addObject("userInfoList", userInfoList)
	            .addObject("tenantOrderType", TenantOrderType.NEW);   
	}
	
	
	
	/**
	 * 续费
	 * 
	 * @return ModelAndView
	 */	
	@Func(funcCode="add", moduleCode="mgr.tenant", enableLog=false, enablePermission=false)  
	@RequestMapping
	public ModelAndView renewOrder(@RequestParam int tenantId){
		Tenant tenant = tenantMgrService.load(tenantId);
		TenantDefConfig tenantDef = TenantTypeConfigManager.getInstance().getTenantDefConfig(tenant.getBagCode());
		List<TenantUserVo> userInfoList = userBizService.findByTenant(tenantId);
	  	return new ModelAndView("/mgr/tenant/renewOrder")
	  			.addObject("tenant", tenant)
	  			.addObject("tenantDef", tenantDef)
	  			.addObject("userInfoList", userInfoList)
	  			.addObject("tenantOrderType", TenantOrderType.RENEW);
	  	
	}
	
	
	
	/**
	 * 增加订单
	 * @param userId
	 * @param tenantTypeCode
	 * @param tenantCode
	 * @param tenantAlias
	 * @param quantity
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="saveOrder.json")
	public ModelAndView saveOrder(@RequestParam int userId,@RequestParam int tenantId,@RequestParam String tenantTypeCode,@RequestParam String tenantCode,@RequestParam int tenantOrderType,
			                      @RequestParam String tenantAlias, @RequestParam int quantity , HttpServletRequest request) throws Exception{      
		
		TenantDefConfig tenantDef = TenantTypeConfigManager.getInstance().getTenantDefConfig(tenantTypeCode);
	    //TODO 隔离级别暂时为共享，后续可在页面增加选项，同时价格上需要区分
	    Integer orderId = tenantOrderMgrService.save(tenantOrderType, tenantId, tenantCode, tenantAlias, tenantTypeCode, IsolatedMode.NO_ISOLATION, tenantDef.getPrice(), quantity, userId);
	    TenantOrder tenantOrder = tenantOrderMgrService.load(orderId);
	    
	    String orderNo = tenantOrder.getOrderNo();
	    
	    //FIXME 模拟付费
	    tenantOrderMgrService.doPaid(orderNo, "alipay");
	    if(tenantOrderType == TenantOrderType.NEW){
	    	int tenatId = tenantBizService.doCreateTenant(tenantOrder);
		    tenantOrder.setTenantId(tenatId);
		    tenantOrderMgrService.update(tenantOrder);
	    	//FIXME 激活租户
			tenantBizService.doActivateNewSpace(orderNo,userId,null);		
	    }else if(tenantOrderType == TenantOrderType.RENEW){
	    	tenantBizService.doReNew(tenantOrder);
	    }
		
	    return new ModelAndView("jsonView"); 
	    
   }
	
	
	
	/**
	 * Show Order.
	 * 
	 * @param id 
	 * @return ModelAndView
	 * 
	 */
	@Func(funcCode="query", moduleCode="mgr.tenant", enableLog=false, enablePermission=false)  
	@RequestMapping 
	public ModelAndView showOrder(@RequestParam Integer id){ 
		
		TenantOrder tenantOrder = tenantOrderMgrService.load(id);
		UserInfo userInfo = userInfoMgrService.load(tenantOrder.getCreateBy());
		
        return new ModelAndView("/mgr/tenantOrder/show")
        		.addObject("tenantOrder", tenantOrder)
        		.addObject("userInfo", userInfo);
    }   
	
	
	
	/**
	 * 查询租户订单
	 * @param id
	 * @param request
	 * @param modelMap
	 * @return
	 * @throws NotLoginException
	 */
	@Func(funcCode="query", moduleCode="mgr.tenant", enableLog=false) 
	@RequestMapping 
	public ModelAndView tenantOrder(@RequestParam int id, WebRequest request, ModelMap modelMap) throws NotLoginException
	{	
		//get params from request
		String code = request.getParameter("code");
		String name = request.getParameter("name");
				
		//package the params
		PageParam pageParam = WebUtils.getPageParam(request);
		pageParam.addCond("tenantId", id);
		pageParam.addCond("code", code);	
		pageParam.addCond("name", name);	
		pageParam.addCond("createBy",LoginUtils.getLoginOpId());
		pageParam.addCond("isDeleted", false);	
		//Get page result
		IPageList pageList = tenantOrderMgrService.listPage(pageParam);		
		
		//return params to response
		modelMap.addAttribute("pageParam", pageParam);	
		modelMap.addAttribute("pageList", pageList);	
		
		return new ModelAndView("/mgr/tenant/tenantOrder")
					.addObject("tenantId", id);	
	
	} 	

	
	
	@Func(funcCode="query",moduleCode="mgr.tenant", enableLog=false)
	@RequestMapping
	public ModelAndView conf(@RequestParam Integer id){		
		Tenant tenant = tenantMgrService.load(id);
		
		Map<Integer, TenantConfigVo> tenantConfMapCache = (Map<Integer, TenantConfigVo>)SimpleCacheManager.getInstance().get(SaapConstants.APP_TENANT_CONFIG);
		
		TenantConfigVo tenantConfig = tenantConfMapCache.get(tenant.getId());
		//读取元数据
		TenantMetaAttrGroup[] metaAttrGroups = TenantMetaConfigManager.getInstance().getAllTenantMetaAttrGroup(); 
		
		return new ModelAndView("/mgr/tenant/conf")
					.addObject("tenant", tenant)
					.addObject("tenantConfig", tenantConfig)
					.addObject("metaAttrGroups", metaAttrGroups);
	}
	
	
	/**
	 * 租户下的成员
	 * @param id
	 * @param modelMap
	 * @return
	 * @throws NotLoginException
	 */
	@Func(funcCode="query",moduleCode="mgr.tenant", enableLog=false)
	@RequestMapping
	public ModelAndView confTenantMember(@RequestParam int id, ModelMap modelMap) throws NotLoginException
	{	
		Tenant tenant = tenantMgrService.load(id);
		List tenantMemberList = tenantMemberMgrService.queryByTenantId(id);
	    return new ModelAndView("/mgr/tenant/confMember")
	    		.addObject("tenant", tenant)
	    		.addObject("tenantMemberList", tenantMemberList);
	}  
	
	
	/**
	 * 配置空间.
	 * 
	 * @throws Exception
	 */
	@Func(funcCode = "edit", moduleCode = "mgr.tenant")
	@RequestMapping
	public ModelAndView config(@RequestParam String tenantAlias, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		int tenantId = LoginUtils.getTenantId();
		tenantMgrService.update(tenantId, tenantAlias); // 更新租户别名

		Map<String, String> paramMap = new HashMap<String, String>();
		// 读取元数据
		TenantMetaAttrGroup[] metaAttrGroups = TenantMetaConfigManager.getInstance().getAllTenantMetaAttrGroup();
		for (TenantMetaAttrGroup attrGroup : metaAttrGroups) {
			String code = attrGroup.getCode();
			TenantMetaAttr[] attrs = attrGroup.getAttrList();
			for (TenantMetaAttr attr : attrs) {
				String fieldName = code + "_" + attr.getKey();
				String value = request.getParameter(fieldName);
				paramMap.put(code + "." + attr.getKey(), value);
			}
		}

		tenantConfigMgrService.updateBatch(tenantId, metaAttrGroups, paramMap);

		return new ModelAndView("jsonView");
	}
	
	
	/**
	 * Show Page.
	 * 
	 * @param id member's id
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="query", moduleCode="mgr.tenant", enableLog=false)  
	@RequestMapping 
	public ModelAndView showMemberDetail(@RequestParam Integer id) 
	{ 
		TenantMember tenantMember = tenantMemberMgrService.load(id);		
		UserInfo userInfo = userInfoMgrService.load(tenantMember.getUserId());
		
		List<Role> userRoleList = userBizService.listByUserRoleAndTenant(tenantMember.getUserId(), tenantMember.getTenantId());
		List<UserGroup> userGroupList = userGroupMgrService.listByTenantAndUser(tenantMember.getTenantId(), tenantMember.getUserId());
		
        return new ModelAndView("/mgr/tenant/showMemberDetail")
					.addObject("tenantMember", tenantMember)
					.addObject("userInfo", userInfo)
					.addObject("userRoleList", userRoleList)
					.addObject("userGroupList", userGroupList);
    } 
	
	
	/**
	 * Delete Batch.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode = "edit", moduleCode = "mgr.tenant")
	@RequestMapping
	public void deleteBatch(@RequestParam(value = "ids[]") Integer[] ids) throws Exception {
		tenantMgrService.updateBatch(ids, TenantStatus.DELETED);
	}
	
	
	
	/**
	 * Disabled Batch.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode = "edit", moduleCode = "mgr.tenant")
	@RequestMapping
	public void disableBatch(@RequestParam(value = "ids[]") Integer[] ids) throws Exception {
		tenantMgrService.updateBatch(ids, TenantStatus.DISABLED);
	}
	
	
	/**
	 * Normal Batch.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode = "edit", moduleCode = "mgr.tenant")
	@RequestMapping
	public void normalBatch(@RequestParam(value = "ids[]") Integer[] ids) throws Exception {
		tenantMgrService.updateBatch(ids, TenantStatus.NORMAL);
	}
	

	
	/**
	 * Edit Page.
	 * 
	 * @param id 
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="edit",moduleCode="mgr.tenant", enableLog=false)
	@RequestMapping 
	public ModelAndView edit(@RequestParam Integer id) throws NotLoginException 
	{ 
		Tenant tenant = tenantMgrService.load(id);
		tenantConfigMgrService.load(id);
		
		return new ModelAndView("/mgr/tenant/edit").addObject("tenant", tenant);
    }	
    
	
	
	/**
	 * Show Page.
	 * 
	 * @param id 
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="query",moduleCode="mgr.tenant", enableLog=false)
	@RequestMapping 
	public ModelAndView show(@RequestParam Integer id) throws NotLoginException
	{ 
		Tenant tenant = tenantMgrService.load(id);	
		
		return new ModelAndView("/mgr/tenant/show")
        			.addObject("tenant", tenant);
    }   
	
	
	
	/**
	 * 更新.
	 * @param request 
	 * @param modelMap
	 * @throws Exception 
	 */
	@Func(funcCode="edit",moduleCode="mgr.tenant")
	@RequestMapping 
	public void update(WebRequest request, ModelMap modelMap) throws Exception
	{
		/*Customer customer = customerService.load(Utility.parseInt(request.getParameter("customer_id")));

		BeanUtils.populate(customer, WebUtils.getParametersStartingWith(request, "customer_"));
		
		customer.setUpdateBy(super.getLoginOpId().intValue());*/
		
		Tenant tenant = new Tenant();
		
		tenantMgrService.update(tenant);
	}
	
	
	
	/**
	 * 删除.
	 * @param request 
	 * @param modelMap
	 * @throws Exception 
	 */
	@Func(funcCode="edit",moduleCode = "mgr.tenant")
	@RequestMapping 
	public void delete(@RequestParam Integer id) throws Exception
	{
		Tenant tenant = tenantMgrService.load(id);
		if(tenant != null){
			tenant.setStatus(TenantStatus.DELETED);
			tenantMgrService.update(tenant);
		}
		
	}
	
	
	
	/**
	 * 冻结.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode="edit",moduleCode = "mgr.tenant")
	@RequestMapping 
	public void disabled(@RequestParam Integer id) throws Exception{
		Tenant tenant = tenantMgrService.load(id);
		if(tenant != null){
			tenant.setStatus(TenantStatus.DISABLED);
			tenantMgrService.update(tenant);
		}
	}
	
	
	
	/**
	 * 开通.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode="edit",moduleCode = "mgr.tenant")
	@RequestMapping 
	public void beNormal(@RequestParam Integer id) throws Exception{
		Tenant tenant = tenantMgrService.load(id);
		if(tenant != null){
			tenant.setStatus(TenantStatus.NORMAL);
			tenantMgrService.update(tenant);
		}
	}
	
}
